<?php

/*
  |--------------------------------------------------------------------------
  | Register The Laravel Class Loader
  |--------------------------------------------------------------------------
  |
  | In addition to using Composer, you may use the Laravel class loader to
  | load your controllers and models. This is useful for keeping all of
  | your classes in the "global" namespace without Composer updating.
  |
 */

ClassLoader::addDirectories(array(
    app_path() . '/commands',
    app_path() . '/controllers',
    app_path() . '/models',
    app_path() . '/database/seeds',
));

/*
  |--------------------------------------------------------------------------
  | Application Error Logger
  |--------------------------------------------------------------------------
  |
  | Here we will configure the error logger setup for the application which
  | is built on top of the wonderful Monolog library. By default we will
  | build a basic log file setup which creates a single file for logs.
  |
 */

Log::useFiles(storage_path() . '/logs/laravel.log');

/*
  |--------------------------------------------------------------------------
  | Application Error Handler
  |--------------------------------------------------------------------------
  |
  | Here you may handle any errors that occur in your application, including
  | logging them or displaying custom views for specific errors. You may
  | even register several error handlers to handle different types of
  | exceptions. If nothing is returned, the default error view is
  | shown, which includes a detailed stack trace during debug.
  |
 */

App::error(function(Exception $exception, $code) {
    //return Redirect::route('error-pages')->with(['code' => $code, 'message' => $exception->getMessage()]);
    Log::error($exception);
});

/*
  |--------------------------------------------------------------------------
  | Maintenance Mode Handler
  |--------------------------------------------------------------------------
  |
  | The "down" Artisan command gives you the ability to put an application
  | into maintenance mode. Here, you will define what is displayed back
  | to the user if maintenance mode is in effect for the application.
  |
 */

App::down(function() {
    return Response::make("Be right back!", 503);
});

/*
  |--------------------------------------------------------------------------
  | Require The Filters File
  |--------------------------------------------------------------------------
  |
  | Next we will load the filters file for the application. This gives us
  | a nice separate location to store our route and application filter
  | definitions instead of putting them all in the main routes file.
  |
 */

require app_path() . '/filters.php';

class CNamHoa extends Illuminate\Support\Str {

    /**
     * Generate a URL friendly "slug" and "translate" from a given string.
     *
     * @param  string  $title
     * @return string
     */
    public static function slugNH($title) {
        return Str::slug(trans($title));
    }

    /**
     * Format Date
     *
     * @param  string $needles
     * @return string
     */
    public static function ConvertDate($needles) {
        if (preg_match('/(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)$/', $needles)) {
            return preg_replace('/(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)$/', '$3-$2-$1 $4:$5:$6', $needles);
        }
        return preg_replace('/(\d+)-(\d+)-(\d+)$/', '$3-$2-$1', $needles);
    }

    /**
     * Get Current Course
     *
     * @return string
     */
    public static function CurrentCourse() {

        return date('Y');
    }

    /**
     * Get Week Days
     * @param string $startDate
     * @param string $endDate
     * @param int $weekdayNumber
     * @return dateArr 
     */
    public static function SpecificDayBetweenDates($startDate = null, $endDate = null, $weekdayNumber = 0) {
        $startDate = $startDate ? strtotime($startDate) : strtotime('-3day');
        $endDate   = $endDate ? strtotime($endDate) : strtotime('+6day', $startDate);
        $dateArr   = [];

        do {
            if (date("w", $startDate) != $weekdayNumber) {
                $startDate += (24 * 3600); // add 1 day
            }
        } while (date("w", $startDate) != $weekdayNumber);

        while ($startDate <= $endDate) {
            $dateArr[] = date('Y-m-d', $startDate);
            $startDate += (7 * 24 * 3600); // add 7 days
        }

        return($dateArr);
    }

    /**
     * Get Rank base on Score
     * @param int $iScore
     * @return o_rank 
     */
    public static function getChuyenCanRank($iScore) {

        if ($iScore >= 8) {
            return 'Tốt';
        } else if ($iScore >= 6.5) {
            return 'Khá';
        } else if ($iScore >= 5) {
            return 'Trung Bình';
        } else {
            return 'Yếu';
        }
    }

    /**
     * Get Rank base on Score
     * @param int $iScore
     * @return o_rank 
     */
    public static function getHocLucRank($iScore) {

        if ($iScore >= 8) {
            return 'Giỏi';
        } else if ($iScore >= 6.5) {
            return 'Khá';
        } else if ($iScore >= 5) {
            return 'Trung Bình';
        } else {
            return 'Yếu';
        }
    }

    /**
     * Generate User ID
     * @param string $sUserType
     * @return sID
     */
    public static function generateUserID($sUserType = 'THI_SINH') {

        switch ($sUserType) {
            case 'QUAN_TRI':
                $sNewID = 'QT';
                break;

            case 'TINH_NGUYEN_VIEN':
                $sNewID = substr(CNamHoa::CurrentCourse(), -2);
                break;

            default:
                $sNewID = substr(CNamHoa::CurrentCourse(), -2);
                break;
        }

        $iCountID = User::where('id', 'like', "$sNewID%")->max('id');
        $iCountID = $iCountID ? (int) substr($iCountID, -3) : 0;
        $iCountID++;

        $sNewID .= strlen($iCountID) < 3 ? str_repeat(0, 3 - strlen($iCountID)) . $iCountID : $iCountID;

        return $sNewID;
    }

    /**
     * Check Permission
     * @param string $routeName
     * @return boolean
     */
    public static function checkPermission($routeName, $aTempOptions = []) {

        if (Auth::user()->id == 'admin')
            return true;

        $aOptions = [
            'isPost' => true,
        ];

        $aOptions = array_merge($aOptions, $aTempOptions);

        switch ($routeName) {
            // case 'error-pages':
            // case 'set-lang':
            // case 'login':
            // case 'logout':
            // case 'home':
            // case 'profile':
            // case 'profile-get-image':
            case 'profile-form':
            case 'profile-password':
            case 'profile-image':
            case 'profile-create-brother':
            case 'profile-table-brother':
            case 'profile-remove-brother':
            case 'profile-create-dear':
            case 'profile-table-dear':
            case 'profile-edit-dear':
            case 'profile-remove-dear':
                if (!Entrust::can('manage-User') && $aOptions['isPost']) {
                    if (Route::input('id') != Auth::user()->id) {
                        return false;
                    }
                }
                break;

            case 'user-list':
                if ($aOptions['isPost']) {
                    switch (Input::get('sGroupActionName')) {
                        case 'delete':
                        case 'setclass':
                            if (!Entrust::can('manage-User')) {
                                return false;
                            }
                            break;

                        case 'assign_permission':
                            if (!Entrust::can('permission')) {
                                return false;
                            }
                            break;

                        default:
                            break;
                    }
                }
                break;

            case 'create-user':
            case 'create-user-by-file':
            case 'create-user-by-file-table':
            case 'create-user-by-file-edit':
                if (!Entrust::can('manage-User-Create') && $aOptions['isPost']) {
                    return false;
                }
                break;

            //case 'attendance-user':
            //case 'attendance-form':
            case 'attendance-update':
                if (!Entrust::can('manage-User-Attendance') && $aOptions['isPost']) {
                    return false;
                }
                break;

            //case 'score-user':
            //case 'score-form':
            case 'score-update':
                if (!Entrust::can('manage-User-Attendance-Score') && $aOptions['isPost']) {
                    return false;
                }
                break;

            //case 'review-page':
            //case 'review-load-user':
            //case 'review-form':
            case 'review-update':
                if (!Entrust::can('manage-User-Review') && $aOptions['isPost']) {
                    return false;
                }
                break;

            case 'document':
                if (!Entrust::can('manage-Document') && $aOptions['isPost']) {
                    return false;
                }
                break;

            case 'permission-assign-list':
                if ($aOptions['isPost']) {
                    switch (Input::get('sGroupActionName')) {
                        case 'delete':
                            if (!Entrust::can('permission')) {
                                return false;
                            }
                            break;

                        default:
                            break;
                    }
                }
                break;

            // case 'permission-load':
            case 'permission-create':
            case 'permission-edit':
            case 'permission-remove':
                if (!Entrust::can('permission') && $aOptions['isPost']) {
                    return false;
                }
                break;

            // case 'option-load':
            case 'option-create':
            case 'option-edit':
                if (!Entrust::can('system-option') && $aOptions['isPost']) {
                    return false;
                }
                break;
            case 'option-remove':
                return false;
                break;

            case 'class-list':
                if ($aOptions['isPost']) {
                    switch (Input::get('sGroupActionName')) {
                        case 'delete':
                            if (!Entrust::can('manage-Class')) {
                                return false;
                            }
                            break;

                        default:
                            break;
                    }
                }
                break;

            case 'class-create':
            case 'class-edit':
            //case 'class-detail-user':
            case 'class-remove-user':
                if (!Entrust::can('manage-Class') && $aOptions['isPost']) {
                    return false;
                }
                break;

            default:
                break;
        }

        return true;
    }

    /**
     * Get Hide/Show Class From Checking Permission
     * @param string $routeName
     * @return string $className
     */
    public static function getHideClass($routeName, $aTempOptions = []) {
        $aOptions = [
            'addClass'       => 'disabled',
            'parameterInput' => [],
        ];

        $aOptions = array_merge($aOptions, $aTempOptions);

        if ($aOptions['parameterInput'])
            Input::merge($aOptions['parameterInput']);

        if (!CNamHoa::checkPermission($routeName)) {
            return $aOptions['addClass'];
        }
    }

}

Cache::rememberForever('options', function() {

    $Response = [
        'COURSE'       => [], 'LE'           => [], 'HOC'          => [], 'RANK'         => [],
        'DOT_KIEM_TRA' => [], 'LAN_KIEM_TRA' => [], 'USERTYPE'     => [], 'USERCREW'     => [],
        'NGANH'        => [], 'CAP'          => [], 'DOI'          => []
    ];

    try {

        foreach (DB::table('options')->get() as $Object) {

            if (is_object(json_decode($Object->data))) {
                $Object->data = json_decode($Object->data);
            }

            $Response[$Object->type][$Object->key] = $Object;
        }
    } catch (Exception $exc) {
        return $Response;
    }

    return $Response;
});
